package at.codebase.web.util.template;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Logger;

import org.apache.commons.io.FileUtils;

import at.codebase.core.Settings;
import at.codebase.security.SecurePrintWriter;

/**
 * This class is used to create a Template of a single template file. It caches
 * all files for a later reuse.
 * 
 * @author Lukas Pfeifhofer <lukas.pfeifhofer@devlabs.pro>
 * 
 */
public class TemplateEngine {
	
	private static final Logger log = Logger.getLogger(TemplateEngine.class
			.getName());

	private static final String TEMPLATE_FOLDER = "WEB-INF/templates/";

	private static HashMap<String, String> templateCache = new HashMap<String, String>();

	public static Template getTemplate(String templateFileUri) {
		return new Template(getTemplateContent(templateFileUri));
	}

	public static Template getTemplate(String templateFileUri,
			SecurePrintWriter securePrintWriter) {
		return new Template(getTemplateContent(templateFileUri),
				securePrintWriter);
	}

	private static String readFile(String templateFileUri) throws IOException {
		File tfile = new File(TEMPLATE_FOLDER + templateFileUri);
		if (tfile.exists()) {
			return FileUtils.readFileToString(tfile);
		}
		log.severe("Template file["+templateFileUri+"] does not exists");
		
		return null;
	}

	public static String getTemplateContent(String templateFileUri) {
		String templateContent;

		if (templateCache.containsKey(templateFileUri)
				&& Settings.TEMPLATE_FILE_CACHING) {
			templateContent = templateCache.get(templateFileUri);
		} else {
			try {
				templateContent = readFile(templateFileUri);
			} catch (IOException e) {
				log.severe("Template file["+templateFileUri+"] could not be loaded");
				return null;
			}
		}

		if (templateContent == null)
			return null;

		return templateContent;
	}

	public static void clearCache() {
		templateCache.clear();
	}
}
